
import HttpUtil from '../../lib/trilobite/core/httputil.js'

var app = getApp();

let self;
let comp;
let isCheckNum;

/**
 * 获取购物车的数量
 */
class CartListAction {
  constructor() {
    this.http = new HttpUtil(app);
    this.http.addResultListener(this.result);
  }
  result = (res) => {
    if (this.callback) {
      this.callback(res);
    }
  }
  /**
   * 加载接口
   */
  load = () => {
    console.log("缓存:"+wx.getStorageSync('memberId '), app.globalData.userInfo)
    this.http.post("/EsCart/findListByMemberId", { memberId: app.globalData.userInfo.memberId })
  }
}
/**
 * 选中产品
 */
class SelectProductAction {
  //POST /EsCart/checkGoods//
  constructor() {
    this.http = new HttpUtil(app);
    this.http.addResultListener(this.result);
  }
  result = (res) => {
    if (this.callback) {
      this.callback(res);
    }
  }
  /**
   * 加载接口
   */
  load = (productId, ischeck) => {
    this.http.post("/EsCart/checkGoods", { productId: productId, isCheck: ischeck })
  }
}

/**
 * 修改产品数量
 */
class UpdateNumAction {
  //POST /EsCart/checkGoods//
  constructor() {
    this.http = new HttpUtil(app);
    this.http.addResultListener(this.result);
  }
  result = (res) => {
    if (this.callback) {
      this.callback(res);
    }
  }
  /**
   * 加载接口
   */
  load = (cartId, num) => {
    this.http.post("/EsCart/updateNum", { cartId: cartId, num: num })
  }
}
/*
 * 统计购物车价格
*/
class TotalPriceAction {
  //POST /EsCart/checkGoods//
  constructor() {
    this.http = new HttpUtil(app);
    this.http.addResultListener(this.result);
  }
  result = (res) => {
    if (this.callback) {
      this.callback(res);
    }
  }
  /**
   * 加载接口
   */
  load = () => {
    this.http.post("/EsCart/FindPrice", { memberId: app.globalData.userInfo.memberId })
  }
}

/*
 * 选择所有的商品
*/
class SelectAllAction {
  //POST /EsCart/checkGoods//
  constructor() {
    this.http = new HttpUtil(app);
    this.http.addResultListener(this.result);
  }
  result = (res) => {
    if (this.callback) {
      this.callback(res);
    }
  }
  /**
   * 加载接口
   */
  load = (a) => {
    this.http.post("/EsCart/checkAll", { memberId: app.globalData.userInfo.memberId, isCheck: a })
  }
}

/*
 * 删除当前的商品
*/
class DeleteCartIdAction {
  //POST /EsCart/checkGoods//
  constructor() {
    this.http = new HttpUtil(app);
    this.http.addResultListener(this.result);
  }
  result = (res) => {
    if (this.callback) {
      this.callback(res);
    }
  }
  /**
   * 加载接口
   */
  load = (a) => {
    this.http.post("/EsCart/DeleteCardId", { cartId: a })
  }
}

/*
 * 删除选中的商品
*/
class DeleteSelectedAction {
  //POST /EsCart/checkGoods//
  constructor() {
    this.http = new HttpUtil(app);
    this.http.addResultListener(this.result);
  }
  result = (res) => {
    if (this.callback) {
      this.callback(res);
    }
  }
  /**
   * 加载接口
   */
  load = (a) => {
    
    this.http.post("/EsCart/DeleteSelected", { memberId: app.globalData.userInfo.memberId })
  }
}

/**
 * 页面控制器
 */
class PageController {
  constructor() {
    comp = this;
    this.CartListAction = new CartListAction();
    this.CartListAction.callback = this.cartListResult;
    this.SelectProductAction = new SelectProductAction();
    this.UpdateNumAction = new UpdateNumAction();
    this.TotalPriceAction = new TotalPriceAction();
    this.TotalPriceAction.callback = this.totalPrice;
    this.SelectAllAction = new SelectAllAction();
    this.SelectAllAction.callback = (e) => {
      comp.initLoad();
    }
    this.DeleteCartIdAction = new DeleteCartIdAction();
    this.DeleteCartIdAction.callback = (e) => {
      comp.initLoad();
    }
    this.DeleteSelectedAction = new DeleteSelectedAction();
    this.DeleteSelectedAction.callback = (e) => {
      comp.initLoad();
    }


  }

  initLoad = () => {
    comp.CartListAction.load();
   
  }

  totalPrice = (res) => {
    isCheckNum = 0;
    self.data.result.totalPrice = res.data.data[0] ? res.data.data[0] : 0;
    //检查是否全部选中
    
    if (self.data.result.list){
      for (let i = 0; i < self.data.result.list.length;i++){
        
        if (self.data.result.list[i].isCheck == 1){
          isCheckNum++;
        }
      }
        if (isCheckNum == 0) {
          self.data.result.noSelect = true;
          self.data.result.allSelect = false;

        }
        if (isCheckNum > 0 && isCheckNum < self.data.result.list.length) {
          self.data.result.noSelect = false;
          self.data.result.allSelect = false;
        }
        if (isCheckNum == self.data.result.list.length) {
          //全选
          self.data.result.noSelect = false;
          self.data.result.allSelect = true;
        }
        self.setData({ result: self.data.result })
    }
  
   

 
   
  }
  data = {
    result: {
      saveHidden: false,
      list: {},
      totalPrice: 0,
    },
    allSelect: false,
    noSelect: false,
    delBtnWidth: 120,

  }

  delItem = (e) => {
    var index = e.currentTarget.dataset.index;
    var list = self.data.result.list;
    if (index !== "" && index != null) {
      comp.DeleteCartIdAction.load(list[parseInt(index)].cartId);
    }
  }

  deleteSelected = (e) => {
    wx.showModal({
      title: '提示',
      content: '确认删除所选商品吗？',
      success: function (res) {
        if (res.confirm) {
          comp.DeleteSelectedAction.load();
        }
      }
    })
    
  }

  /**
   * 减数量
   */
  jianBtnTap = (e) => {
    var index = e.currentTarget.dataset.index;
    var list = self.data.result.list;
    if (index !== "" && index != null) {
      if (list[parseInt(index)].num > 1) {
        list[parseInt(index)].num = list[parseInt(index)].num - 1;
        comp.UpdateNumAction.callback = () => {
          self.setData({ result: self.data.result })
          //self.setData({ result: { list: list } });
          comp.TotalPriceAction.load();
        }
        comp.UpdateNumAction.load(list[parseInt(index)].cartId, list[parseInt(index)].num);
      }
    }
  }
  /**
   * 加数量
   */
  jiaBtnTap = (e) => {
    var index = e.currentTarget.dataset.index;
    var list = self.data.result.list;
    if (index !== "" && index != null) {
      //if (list[parseInt(index)].num > 0) {
      list[parseInt(index)].num = list[parseInt(index)].num + 1;
      // }
      comp.UpdateNumAction.callback = () => {
        self.setData({ result: self.data.result })
        comp.TotalPriceAction.load();
      }
      comp.UpdateNumAction.load(list[parseInt(index)].cartId, list[parseInt(index)].num);

    }
  }

  cartListResult = (res) => {
    console.log(res.data)
    self.data.result.list = res.data.data;
    self.setData({ result: { list: self.data.result.list, saveHidden: false } });
    // 加载列表完成后 再计算全选以及价格
    comp.TotalPriceAction.load();
  }
  onLoad = function () {
    self = this;
    comp.initLoad();
   
   
  }

  editTap = (e) => {
    self.data.result.saveHidden = false;
    self.setData({ result: self.data.result });

  }
  saveTap = (e) => {
    self.data.result.saveHidden = true;
    self.setData({ result: self.data.result });
  }

  touchS = (e) => {
    if (e.touches.length == 1) {
      self.setData({
        startX: e.touches[0].clientX
      });
    }
  }

  touchM = (e) => {
    var index = e.currentTarget.dataset.index;

    if (e.touches.length == 1) {
      var moveX = e.touches[0].clientX;
      var disX = self.data.startX - moveX;
      var delBtnWidth = self.data.delBtnWidth;
      var left = "";
      if (disX == 0 || disX < 0) {//如果移动距离小于等于0，container位置不变
        left = "margin-left:0px";
      } else if (disX > 0) {//移动距离大于0，container left值等于手指移动距离
        left = "margin-left:-" + disX + "px";
        if (disX >= delBtnWidth) {
          left = "left:-" + delBtnWidth + "px";
        }
      }
      var list = self.data.result.list;
      if (index != "" && index != null) {
        list[parseInt(index)].left = left;
        self.setData({ result: self.data.result });
        // this.setGoodsList(this.getSaveHide(),this.totalPrice(),this.allSelect(),this.noSelect(),list);
      }
    }
  }

  touchE = (e) => {
    var index = e.currentTarget.dataset.index;
    if (e.changedTouches.length == 1) {
      var endX = e.changedTouches[0].clientX;
      var disX = self.data.startX - endX;
      var delBtnWidth = self.data.delBtnWidth;
      //如果距离小于删除按钮的1/2，不显示删除按钮
      var left = disX > delBtnWidth / 2 ? "margin-left:-" + delBtnWidth + "px" : "margin-left:0px";
      var list = self.data.result.list;
      if (index !== "" && index != null) {
        list[parseInt(index)].left = left;
        // this.setGoodsList(this.getSaveHide(),this.totalPrice(),this.allSelect(),this.noSelect(),list);
        self.setData({ result: self.data.result });
        console.log(self.data.result)
      }
    }
  }
  /**
   * 选择购物车物品
   */
  selectTap = (e) => {
    var index = e.currentTarget.dataset.index;
    var list = self.data.result.list;
    if (index !== "" && index != null) {
      if (list[parseInt(index)].isCheck === 1) {
        list[parseInt(index)].isCheck = 0;
      } else {
        list[parseInt(index)].isCheck = 1;
      }
      comp.SelectProductAction.callback = () => {
        self.setData({ result: { list: list } });
        comp.TotalPriceAction.load();
        
      }

      comp.SelectProductAction.load(list[parseInt(index)].productId, list[parseInt(index)].isCheck);
    }
  }

  getEleWidth = (w) => {
    var real = 0;
    try {
      var res = wx.getSystemInfoSync().windowWidth;
      var scale = (750 / 2) / (w / 2);  //以宽度750px设计稿做宽度的自适应
      // console.log(scale);
      real = Math.floor(res / scale);
      return real;
    } catch (e) {
      return false;
      // Do something when catch error
    }
  }
  initEleWidth = () => {
    var delBtnWidth = comp.getEleWidth(self.data.delBtnWidth);
    self.setData({
      delBtnWidth: delBtnWidth
    });
  }
  onShow = function(){
    this.onLoad()
  }
  onLoad = function () {
    self = this;
    comp.initEleWidth();
    comp.CartListAction.load();
    comp.TotalPriceAction.load();
    //this.onShow();
  }

  /**
   * 到首页
   */
  toIndexPage = () => {
    wx.switchTab({
      url: "/pages/index/index"
    });
  }
  toPayOrder = () => {
    wx.navigateTo({
      url: "/pages/to-pay-order/index"
    })
  }


  /**
   * 选择所有的
   */
  bindAllSelect = () => {
    if (self.data.result.allSelect) {
      comp.SelectAllAction.load(0);
    } else {
      comp.SelectAllAction.load(1);
    }
  }
}

Page(new PageController());

// Page({
//   data: {
//     goodsList:{
//       saveHidden:true,
//       totalPrice:0,
//       totalScoreToPay: 0,
//       allSelect:true,
//       noSelect:false,
//       list:[]
//     },
//     delBtnWidth:120,    //删除按钮宽度单位（rpx）
//   },

//  //获取元素自适应后的实际宽度
//   getEleWidth:function(w){
//     var real = 0;
//     try {
//       var res = wx.getSystemInfoSync().windowWidth;
//       var scale = (750/2)/(w/2);  //以宽度750px设计稿做宽度的自适应
//       // console.log(scale);
//       real = Math.floor(res/scale);
//       return real;
//     } catch (e) {
//       return false;
//      // Do something when catch error
//     }
//   },
//   initEleWidth:function(){
//     var delBtnWidth = this.getEleWidth(this.data.delBtnWidth);
//     this.setData({
//       delBtnWidth:delBtnWidth
//     });
//   },
//   onLoad: function () {
//       this.initEleWidth();
//       this.onShow();
//   },
//   onShow: function(){
//       var shopList = [];
//       // 获取购物车数据
//       var shopCarInfoMem = wx.getStorageSync('shopCarInfo');
//       if (shopCarInfoMem && shopCarInfoMem.shopList) {
//         shopList = shopCarInfoMem.shopList
//       }
//       this.data.goodsList.list = shopList;
//       this.setGoodsList(this.getSaveHide(),this.totalPrice(),this.allSelect(),this.noSelect(),shopList);
//   },
//   toIndexPage:function(){
//       wx.switchTab({
//             url: "/pages/index/index"
//       });
//   },

//   touchS:function(e){
//     if(e.touches.length==1){
//       this.setData({
//         startX:e.touches[0].clientX
//       });
//     }
//   },
//   touchM:function(e){
//   var index = e.currentTarget.dataset.index;

//     if(e.touches.length==1){
//       var moveX = e.touches[0].clientX;
//       var disX = this.data.startX - moveX;
//       var delBtnWidth = this.data.delBtnWidth;
//       var left = "";
//       if(disX == 0 || disX < 0){//如果移动距离小于等于0，container位置不变
//         left = "margin-left:0px";
//       }else if(disX > 0 ){//移动距离大于0，container left值等于手指移动距离
//         left = "margin-left:-"+disX+"px";
//         if(disX>=delBtnWidth){
//           left = "left:-"+delBtnWidth+"px";
//         }
//       }
//       var list = this.data.goodsList.list;
//       if(index!="" && index !=null){
//         list[parseInt(index)].left = left; 
//         this.setGoodsList(this.getSaveHide(),this.totalPrice(),this.allSelect(),this.noSelect(),list);
//       }
//     }
//   },

//   touchE:function(e){
//     var index = e.currentTarget.dataset.index;    
//     if(e.changedTouches.length==1){
//       var endX = e.changedTouches[0].clientX;
//       var disX = this.data.startX - endX;
//       var delBtnWidth = this.data.delBtnWidth;
//       //如果距离小于删除按钮的1/2，不显示删除按钮
//       var left = disX > delBtnWidth/2 ? "margin-left:-"+delBtnWidth+"px":"margin-left:0px";
//       var list = this.data.goodsList.list;
//      if(index!=="" && index != null){
//         list[parseInt(index)].left = left; 
//         this.setGoodsList(this.getSaveHide(),this.totalPrice(),this.allSelect(),this.noSelect(),list);

//       }
//     }
//   },
//   delItem:function(e){
//     var index = e.currentTarget.dataset.index;
//     var list = this.data.goodsList.list;
//     list.splice(index,1);
//     this.setGoodsList(this.getSaveHide(),this.totalPrice(),this.allSelect(),this.noSelect(),list);
//   },
//   selectTap:function(e){
//     var index = e.currentTarget.dataset.index;
//     var list = this.data.goodsList.list;
//     if(index!=="" && index != null){
//         list[parseInt(index)].active = !list[parseInt(index)].active ; 
//         this.setGoodsList(this.getSaveHide(),this.totalPrice(),this.allSelect(),this.noSelect(),list);
//       }
//    },
//    totalPrice:function(){
//       var list = this.data.goodsList.list;
//       var total = 0;
//       let totalScoreToPay = 0;
//       for(var i = 0 ; i < list.length ; i++){
//           var curItem = list[i];
//           if(curItem.active){
//             total+= parseFloat(curItem.price)*curItem.number;
//             totalScoreToPay += curItem.score * curItem.number;
//           }
//       }
//       this.data.goodsList.totalScoreToPay = totalScoreToPay;
//       total = parseFloat(total.toFixed(2));//js浮点计算bug，取两位小数精度
//       return total;
//    },
//    allSelect:function(){
//       var list = this.data.goodsList.list;
//       var allSelect = false;
//       for(var i = 0 ; i < list.length ; i++){
//           var curItem = list[i];
//           if(curItem.active){
//             allSelect = true;
//           }else{
//              allSelect = false;
//              break;
//           }
//       }
//       return allSelect;
//    },
//    noSelect:function(){
//       var list = this.data.goodsList.list;
//       var noSelect = 0;
//       for(var i = 0 ; i < list.length ; i++){
//           var curItem = list[i];
//           if(!curItem.active){
//             noSelect++;
//           }
//       }
//       if(noSelect == list.length){
//          return true;
//       }else{
//         return false;
//       }
//    },
//    setGoodsList:function(saveHidden,total,allSelect,noSelect,list){
//      this.setData({
//         goodsList:{
//           saveHidden:saveHidden,
//           totalPrice:total,
//           allSelect:allSelect,
//           noSelect:noSelect,
//           list:list,
//           totalScoreToPay: this.data.goodsList.totalScoreToPay
//         }
//       });
//       var shopCarInfo = {};
//       var tempNumber = 0;
//       shopCarInfo.shopList = list;
//       for(var i = 0;i<list.length;i++){
//         tempNumber = tempNumber + list[i].number
//       }
//       shopCarInfo.shopNum = tempNumber;
//       wx.setStorage({
//         key:"shopCarInfo",
//         data:shopCarInfo
//       })
//    },
//    bindAllSelect:function(){
//       var currentAllSelect = this.data.goodsList.allSelect;
//       var list = this.data.goodsList.list;
//       if(currentAllSelect){
//         for(var i = 0 ; i < list.length ; i++){
//             var curItem = list[i];
//             curItem.active = false;
//         }
//       }else{
//         for(var i = 0 ; i < list.length ; i++){
//             var curItem = list[i];
//             curItem.active = true;
//         }
//       }

//       this.setGoodsList(this.getSaveHide(),this.totalPrice(),!currentAllSelect,this.noSelect(),list);
//    },
//    jiaBtnTap:function(e){
//     var index = e.currentTarget.dataset.index;
//     var list = this.data.goodsList.list;
//     if(index!=="" && index != null){
//       if(list[parseInt(index)].number<10){
//         list[parseInt(index)].number++; 
//         this.setGoodsList(this.getSaveHide(),this.totalPrice(),this.allSelect(),this.noSelect(),list);
//       }
//     }
//    },
//    jianBtnTap:function(e){
//     var index = e.currentTarget.dataset.index;
//     var list = this.data.goodsList.list;
//     if(index!=="" && index != null){
//       if(list[parseInt(index)].number>1){
//         list[parseInt(index)].number-- ;
//         this.setGoodsList(this.getSaveHide(),this.totalPrice(),this.allSelect(),this.noSelect(),list);
//       }
//     }
//    },
//    editTap:function(){
//      var list = this.data.goodsList.list;
//      for(var i = 0 ; i < list.length ; i++){
//             var curItem = list[i];
//             curItem.active = false;
//      }
//      this.setGoodsList(!this.getSaveHide(),this.totalPrice(),this.allSelect(),this.noSelect(),list);
//    },
//    saveTap:function(){
//      var list = this.data.goodsList.list;
//      for(var i = 0 ; i < list.length ; i++){
//             var curItem = list[i];
//             curItem.active = true;
//      }
//      this.setGoodsList(!this.getSaveHide(),this.totalPrice(),this.allSelect(),this.noSelect(),list);
//    },
//    getSaveHide:function(){
//      var saveHidden = this.data.goodsList.saveHidden;
//      return saveHidden;
//    },
//    deleteSelected:function(){
//       var list = this.data.goodsList.list;
//      /*
//       for(let i = 0 ; i < list.length ; i++){
//             let curItem = list[i];
//             if(curItem.active){
//               list.splice(i,1);
//             }
//       }
//       */
//      // above codes that remove elements in a for statement may change the length of list dynamically
//      list = list.filter(function(curGoods) {
//         return !curGoods.active;
//      });
//      this.setGoodsList(this.getSaveHide(),this.totalPrice(),this.allSelect(),this.noSelect(),list);
//     },
//     toPayOrder:function(){
//       wx.showLoading();
//       var that = this;
//       if (this.data.goodsList.noSelect) {
//         wx.hideLoading();
//         return;
//       }
//       // 重新计算价格，判断库存
//       var shopList = [];
//       var shopCarInfoMem = wx.getStorageSync('shopCarInfo');
//       if (shopCarInfoMem && shopCarInfoMem.shopList) {
//         // shopList = shopCarInfoMem.shopList
//         shopList = shopCarInfoMem.shopList.filter(entity => {
//           return entity.active;
//         });
//       }
//       if (shopList.length == 0) {
//         wx.hideLoading();
//         return;
//       }
//       var isFail = false;
//       var doneNumber = 0;
//       var needDoneNUmber = shopList.length;
//       for (let i =0; i < shopList.length; i++) {
//         if (isFail) {
//           wx.hideLoading();
//           return;
//         }
//         let carShopBean = shopList[i];
//         // 获取价格和库存
//         if (!carShopBean.propertyChildIds || carShopBean.propertyChildIds == "") {
//           wx.request({
//             url: 'https://api.it120.cc/'+ app.globalData.subDomain +'/shop/goods/detail',
//             data: {
//               id: carShopBean.goodsId
//             },
//             success: function(res) {
//               doneNumber++;
//               if (res.data.data.properties) {
//                 wx.showModal({
//                   title: '提示',
//                   content: res.data.data.basicInfo.name + ' 商品已失效，请重新购买',
//                   showCancel:false
//                 })
//                 isFail = true;
//                 wx.hideLoading();
//                 return;
//               }
//               if (res.data.data.basicInfo.stores < carShopBean.number) {
//                 wx.showModal({
//                   title: '提示',
//                   content: res.data.data.basicInfo.name + ' 库存不足，请重新购买',
//                   showCancel:false
//                 })
//                 isFail = true;
//                 wx.hideLoading();
//                 return;
//               }
//               if (res.data.data.basicInfo.minPrice != carShopBean.price) {
//                 wx.showModal({
//                   title: '提示',
//                   content: res.data.data.basicInfo.name + ' 价格有调整，请重新购买',
//                   showCancel:false
//                 })
//                 isFail = true;
//                 wx.hideLoading();
//                 return;
//               }
//               if (needDoneNUmber == doneNumber) {
//                 that.navigateToPayOrder();
//               }
//             }
//           })
//         } else {
//           wx.request({
//             url: 'https://api.it120.cc/'+ app.globalData.subDomain +'/shop/goods/price',
//             data: {
//               goodsId: carShopBean.goodsId,
//               propertyChildIds:carShopBean.propertyChildIds
//             },
//             success: function(res) {
//               doneNumber++;
//               if (res.data.data.stores < carShopBean.number) {
//                 wx.showModal({
//                   title: '提示',
//                   content: carShopBean.name + ' 库存不足，请重新购买',
//                   showCancel:false
//                 })
//                 isFail = true;
//                 wx.hideLoading();
//                 return;
//               }
//               if (res.data.data.price != carShopBean.price) {
//                 wx.showModal({
//                   title: '提示',
//                   content: carShopBean.name + ' 价格有调整，请重新购买',
//                   showCancel:false
//                 })
//                 isFail = true;
//                 wx.hideLoading();
//                 return;
//               }
//               if (needDoneNUmber == doneNumber) {
//                 that.navigateToPayOrder();
//               }
//             }
//           })
//         }

//       }
//     },
//     navigateToPayOrder:function () {
//       wx.hideLoading();
//       wx.navigateTo({
//         url:"/pages/to-pay-order/index"
//       })
//     }



// })
